package de.dhbw.karlsruhe.picsim.model.commands.impl;


import de.dhbw.karlsruhe.picsim.model.actions.ActionFactory;
import de.dhbw.karlsruhe.picsim.model.actions.PicAction;
import de.dhbw.karlsruhe.picsim.model.memory.RegisterValue;
import de.dhbw.karlsruhe.picsim.model.memory.impl.RegisterValueImpl;
import de.dhbw.karlsruhe.picsim.util.Bits;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.List;


/**
 * Created by IntelliJ IDEA.
 * User: goesen
 * Date: Apr 18, 2010
 * Time: 11:49:27 AM
 */
public final class AddWF extends InstructionSupport {
    private static final Log log = LogFactory.getLog(AddWF.class);

    public AddWF(final boolean targetIsWRegister, final Bits argument) {
        super(targetIsWRegister, true, argument);
    }

    @NotNull
    @Override
    protected RegisterValue getValue(@NotNull final RegisterValue addressedFile, @NotNull final RegisterValue wRegister,
                                     @NotNull final List<PicAction> yourActions,
                                     @NotNull final ActionFactory actionFactory) {
        log.debug("Addwf gets executed");
        final int wFile = wRegister.asInteger();
        final int addressedValue = addressedFile.asInteger();
        final int result = addDigtCarrygedoenst(yourActions, actionFactory, wFile, addressedValue);


        log.debug("result is " + result);
        return RegisterValueImpl.createUnsafe(result);
    }

    public static int addDigtCarrygedoenst(final Collection<PicAction> yourActions, final ActionFactory actionFactory,
                                           final int wFile,
                                           final int addressedValue) {
        final int result = wFile + addressedValue;
        if (result > 255) {
            log.debug("carry flag will be set");
            yourActions.add(actionFactory.setCarryBit());
        } else {
            log.debug("carry flag will be cleared");
            yourActions.add(actionFactory.clearCarryBit());
        }
        //noinspection UnnecessaryParentheses
        if ((wFile % 16) + (addressedValue % 16) > 15) {
            log.debug("digit carry will be set");
            yourActions.add(actionFactory.setDigitCarryBit());
        } else {
            log.debug("digit carry will be cleared");
            yourActions.add(actionFactory.clearDigitCarryBit());
        }
        return result;
    }
}
